import { useEffect, useState } from 'react'
import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { Button, Toast } from 'antd-mobile'
import pic1 from '@imgs/apply-person.png'
import pic2 from '@imgs/apply-company.png'
import classNames from 'classnames'
import { getAccountInfoRequest, addPartyRequest, addAgentRequest, createCaseRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { push } from '@src/redux/reducers/pages'
import { useAppDispatch } from '@src/redux/hook'
import PageLoading from '@components/pageLoading'

// 根据类型和账号信息返回对象
function formatInfoObj (isParty, caseid, userInfo, info) {
  const o = {
    caseid,
    mobile: userInfo.mobile,
    fileid: info.fileid,
    fileid1: info.fileid1,
    name: info.name,
    license: info.license,
    license_type: info.license_type,
    accountid: userInfo.accountid
  }
  if (isParty) {
    o.type = '申请人'
    o.subject_type = '自然人'
    o.tag = JSON.stringify({ subject_type_tag: '国内自然人' })
  } else {
    o.party_type = '申请人'
    o.party = []
  }
  return o
}

async function initData (setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getAccountInfoRequest())
  setLoading(false)
  if (e === null) {
    if (d !== null) {
      setData(d)
    } else {
      Toast.show({ content: '账号信息缺失', duration: 2000 })
    }
  }
}


// 新建当事人
async function addParty (caseid, userInfo, info) {
  const o = formatInfoObj(true, caseid, userInfo, info)
  const [e] = await awaitWrap(addPartyRequest(o))
  if (e !== null) {
    throw new Error(e.message)
  }
}

// 新建当事人
async function addAgent (caseid, userInfo, info) {
  const o = formatInfoObj(false, caseid, userInfo, info)
  const [e] = await awaitWrap(addAgentRequest(o))
  if (e !== null) {
    throw new Error(e.message)
  }
}

async function createCase (type, userInfo, accountInfo, dispatch) {
  if (accountInfo === null) {
    Toast.show({ content: '账号信息缺失' })
    return undefined
  }
  Toast.show({ content: '创建案件中', icon: 'loading', duration: 0 })
  const [e, caseid] = await awaitWrap(createCaseRequest())
  if (e !== null) {
    return undefined
  }
  Toast.clear()
  if (caseid === null) {
    Toast.show({ content: '案号未返回' })
    return undefined
  }
  const addFn = type === '个人' ? addParty : addAgent
  const [err] = await awaitWrap(addFn(caseid, userInfo, accountInfo))
  if (err !== null) {
    return undefined
  }
  Toast.clear()
  dispatch(push({ element: 'caseEdit', meta: { id: caseid } }))
}

function Main () {
  const dispatch = useAppDispatch()
  const [active1, setActive1] = useState(false)
  const [active2, setActive2] = useState(false)
  const [loading, setLoading] = useState(false)
  const [accountInfo, setAccountInfo] = useState(null)
  useEffect(() => {
    initData(setAccountInfo, setLoading).catch(e => console.error(e))
  }, [])
  if (loading) {
    return (
      <PageComponent title='类型选择'>
        <div className={style.container}>
          <PageLoading />
        </div>
      </PageComponent>
    )
  }
  return (
    <PageComponent title='类型选择'>
      <div className={style.container}>
        <div className={style.body}>
          <div className={classNames(style.btn, { [style.active]: active1  })} onClick={() => {
            setActive1(true)
            createCase('个人', accountInfo, accountInfo, dispatch)
            setTimeout(() => {
              setActive1(false)
            }, 150)
          }}>
            <img src={pic1} className={style.pic} />
            <div className={style.content}>
              <div className={style.title}>个人申请</div>
              <div className={style['sub-title']}>自然人自行申请，请点击进入</div>
            </div>
          </div>
          <div className={classNames(style.btn, { [style.active]: active2  })} onClick={() => {
            setActive2(true)
            createCase('代理人', accountInfo, accountInfo, dispatch)
            setTimeout(() => {
              setActive2(false)
            }, 150)
          }}>
            <img src={pic2} className={style.pic} />
            <div className={style.content}>
              <div className={style.title}>代理人申请</div>
              <div className={style['sub-title']}>企业、个体工商户等单位代理人或负责人申请，或个人代理人，请点击进入</div>
            </div>
          </div>
        </div>
      </div>
    </PageComponent>
  )
}

export default Main
